﻿using log4net;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using WebSocketDemo.Middleware;
using WebSocketDemo.Models;

namespace WebSocketDemo.Manager
{
    public class TaskSoundManager
    {

        /// <summary>
        /// Log4net 日志对象
        /// </summary>
        private readonly ILog Log = LogManager.GetLogger(typeof(ChatWebSocketMiddleware));

        /// <summary>
        /// 间隔30s，定时向前端发送提示消息
        /// </summary>
        public void Process()
        {
            try
            {
                Task.Factory.StartNew(() =>
                {
                    while (true)
                    {
                        Thread.Sleep(30 * 1000);
                        var sockets = ChatWebSocketMiddleware._sockets;
                        foreach (var socket in sockets)
                        {
                            if (socket.Value.State == WebSocketState.Open)
                            {
                                var msg = new MsgTemplate
                                {
                                    SenderID = "sys",
                                    ReceiverID = "everyone",
                                    MessageType = "Send",
                                    Content = "测试声音提示"
                                };

                                CancellationToken ct = ChatWebSocketMiddleware._context.RequestAborted;
                                var data = JsonConvert.SerializeObject(msg);
                                var buffer = Encoding.UTF8.GetBytes(data);
                                var segment = new ArraySegment<byte>(buffer);
                                socket.Value.SendAsync(segment, WebSocketMessageType.Text, true, ct);
                            }
                        }
                    }
                });

            }
            catch (Exception ex)
            {
                Log.Error($"新任务提示线程执行出错：{ex.Message}");
            }

        }
    }
}
